<template>
  <div class="order-management">
    <div class="page-header">
      <h1>订单管理</h1>
      <p>查看和管理系统中的所有订单</p>
    </div>

    <!-- 筛选区域 -->
    <div class="filter-bar">
      <el-form :model="filterForm" inline class="filter-form">
        <el-form-item label="订单号">
          <el-input
            v-model="filterForm.order_number"
            placeholder="请输入订单号"
            style="width: 200px"
            clearable
          />
        </el-form-item>

        <el-form-item label="车牌号">
          <el-input
            v-model="filterForm.license_plate"
            placeholder="请输入车牌号"
            style="width: 150px"
            clearable
          />
        </el-form-item>

        <el-form-item label="联系手机号">
          <el-input
            v-model="filterForm.contact_phone"
            placeholder="请输入联系手机号"
            style="width: 150px"
            clearable
          />
        </el-form-item>

        <el-form-item label="订单状态">
          <el-select
            v-model="filterForm.status"
            placeholder="选择状态"
            style="width: 120px"
            clearable
          >
            <el-option
              v-for="option in ORDER_STATUS_OPTIONS"
              :key="option.value"
              :label="option.label"
              :value="option.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="停车场">
          <el-select
            v-model="filterForm.parking_lot_id"
            placeholder="选择停车场"
            style="width: 200px"
            clearable
            filterable
          >
            <el-option
              v-for="lot in parkingLots"
              :key="lot.id"
              :label="lot.name"
              :value="lot.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="创建时间">
          <el-date-picker
            v-model="dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            style="width: 240px"
            @change="handleDateRangeChange"
          />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="handleSearch" :loading="loading">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
          <el-button @click="handleReset">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 数据表格 -->
    <el-card class="table-card">
      <el-table
        :data="tableData"
        :loading="loading"
        stripe
        style="width: 100%"
      >
        <el-table-column prop="order_number" label="订单号" width="180" show-overflow-tooltip />

        <el-table-column prop="parking_lot_name" label="停车场名称" min-width="150" show-overflow-tooltip />

        <el-table-column prop="user_nickname" label="下单用户" width="120">
          <template #default="{ row }">
            <div class="user-info">
              <span>{{ row.user_nickname || '未知用户' }}</span>
              <div class="user-phone">{{ row.user_phone || '' }}</div>
            </div>
          </template>
        </el-table-column>

        <el-table-column prop="license_plate" label="车牌号" width="100" />

        <el-table-column prop="contact_phone" label="联系手机号" width="120">
          <template #default="{ row }">
            <span v-if="row.contact_phone" class="contact-phone" @click="callPhone(row.contact_phone)">
              {{ row.contact_phone }}
            </span>
            <span v-else class="no-phone">-</span>
          </template>
        </el-table-column>

        <el-table-column prop="parking_type" label="停车类型" width="100" align="center">
          <template #default="{ row }">
            <el-tag :type="row.parking_type === 'outdoor' ? 'warning' : 'primary'" size="small">
              {{ row.parking_type === 'outdoor' ? '室外' : '室内' }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column prop="total_amount" label="总金额" width="100" align="right">
          <template #default="{ row }">
            <span class="amount">¥{{ Number(row.total_amount).toFixed(2) }}</span>
          </template>
        </el-table-column>

        <el-table-column prop="final_amount" label="实付金额" width="100" align="right">
          <template #default="{ row }">
            <span class="amount final-amount">¥{{ Number(row.final_amount).toFixed(2) }}</span>
          </template>
        </el-table-column>

        <el-table-column prop="status" label="订单状态" width="100" align="center">
          <template #default="{ row }">
            <el-tag :type="getOrderStatusTagType(row.status)" size="small">
              {{ getOrderStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>



        <el-table-column prop="created_at" label="创建时间" width="160">
          <template #default="{ row }">
            {{ formatDate(row.created_at) }}
          </template>
        </el-table-column>

        <el-table-column label="操作" width="100" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="handleViewDetail(row)">
              详情
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-wrapper">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 订单详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="订单详情"
      width="800px"
      :close-on-click-modal="false"
    >
      <div v-if="currentOrder" class="order-detail">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="订单号">
            {{ currentOrder.order_number }}
          </el-descriptions-item>
          <el-descriptions-item label="订单状态">
            <el-tag :type="getOrderStatusTagType(currentOrder.status)">
              {{ getOrderStatusText(currentOrder.status) }}
            </el-tag>
          </el-descriptions-item>

          <el-descriptions-item label="支付方式">
            {{ formatPaymentMethod(currentOrder.payment_method) }}
          </el-descriptions-item>
          <el-descriptions-item label="停车场">
            {{ currentOrder.parking_lot_name }}
          </el-descriptions-item>
          <el-descriptions-item label="停车场地址">
            {{ currentOrder.parking_lot_address || '无' }}
          </el-descriptions-item>
          <el-descriptions-item label="用户昵称">
            {{ currentOrder.user_nickname || '未知用户' }}
          </el-descriptions-item>
          <el-descriptions-item label="用户手机">
            {{ currentOrder.user_phone || '无' }}
          </el-descriptions-item>
          <el-descriptions-item label="车牌号">
            {{ currentOrder.license_plate }}
          </el-descriptions-item>
          <el-descriptions-item label="联系手机号" v-if="currentOrder.contact_phone">
            <span class="contact-phone" @click="callPhone(currentOrder.contact_phone)">
              {{ currentOrder.contact_phone }}
            </span>
          </el-descriptions-item>
          <el-descriptions-item label="停车类型">
            <el-tag :type="currentOrder.parking_type === 'outdoor' ? 'warning' : 'primary'" size="small">
              {{ currentOrder.parking_type === 'outdoor' ? '室外停车' : '室内停车' }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="预计入场时间">
            {{ formatDateTime(currentOrder.planned_start_time) }}
          </el-descriptions-item>
          <el-descriptions-item label="预计离场时间">
            {{ formatDateTime(currentOrder.planned_end_time) }}
          </el-descriptions-item>
          <el-descriptions-item label="实际入场时间">
            {{ currentOrder.actual_start_time ? formatDateTime(currentOrder.actual_start_time) : '未入场' }}
          </el-descriptions-item>
          <el-descriptions-item label="实际离场时间">
            {{ currentOrder.actual_end_time ? formatDateTime(currentOrder.actual_end_time) : '未离场' }}
          </el-descriptions-item>
        </el-descriptions>

        <!-- 费用明细区块 -->
        <div class="fee-details-section">
          <h4>费用明细</h4>
          <el-descriptions :column="2" border size="small">
            <el-descriptions-item label="停车天数" v-if="currentOrder.duration_days">
              {{ currentOrder.duration_days }} 天
            </el-descriptions-item>
            <el-descriptions-item label="停车费用">
              <span class="amount">¥{{ Number(currentOrder.total_amount).toFixed(2) }}</span>
            </el-descriptions-item>
            <el-descriptions-item label="优惠金额" v-if="currentOrder.discount_amount > 0">
              <span class="discount">-¥{{ Number(currentOrder.discount_amount).toFixed(2) }}</span>
            </el-descriptions-item>
            <el-descriptions-item label="实付金额">
              <span class="amount final-amount">¥{{ Number(currentOrder.final_amount).toFixed(2) }}</span>
            </el-descriptions-item>
            <el-descriptions-item label="计费说明" v-if="currentOrder.price_description" :span="2">
              <span class="description-text">{{ currentOrder.price_description }}</span>
            </el-descriptions-item>
          </el-descriptions>
        </div>

        <!-- 优惠券信息区块 -->
        <div class="coupon-section" v-if="currentOrder.coupon_info || currentOrder.coupon_name">
          <h4>优惠券信息</h4>
          <el-descriptions :column="2" border size="small">
            <el-descriptions-item label="优惠券名称">
              {{ currentOrder.coupon_info?.name || currentOrder.coupon_name }}
            </el-descriptions-item>
            <el-descriptions-item label="优惠金额">
              <span class="discount">-¥{{ Number(currentOrder.coupon_info?.discount_amount || currentOrder.discount_amount).toFixed(2) }}</span>
            </el-descriptions-item>
            <el-descriptions-item label="优惠券类型" v-if="currentOrder.coupon_info?.type || currentOrder.coupon_type">
              {{ formatCouponType(currentOrder.coupon_info?.type || currentOrder.coupon_type) }}
            </el-descriptions-item>
            <el-descriptions-item label="优惠券面值" v-if="currentOrder.coupon_info?.value || currentOrder.coupon_value">
              {{ formatCouponValue(currentOrder.coupon_info?.type || currentOrder.coupon_type, currentOrder.coupon_info?.value || currentOrder.coupon_value) }}
            </el-descriptions-item>
          </el-descriptions>
        </div>

        <!-- 时间信息 -->
        <div class="time-info-section">
          <h4>时间信息</h4>
          <el-descriptions :column="2" border size="small">
            <el-descriptions-item label="创建时间">
              {{ formatDateTime(currentOrder.created_at) }}
            </el-descriptions-item>
            <el-descriptions-item label="更新时间">
              {{ formatDateTime(currentOrder.updated_at) }}
            </el-descriptions-item>
          </el-descriptions>
        </div>

        <!-- 尾款记录详情 -->
        <div v-if="getAdditionalPayments(currentOrder.payment_method).length > 0" class="additional-payments-section">
          <h4>尾款记录</h4>
          <el-table :data="getAdditionalPayments(currentOrder.payment_method)" size="small" border>
            <el-table-column prop="out_trade_no" label="交易号" width="180" />
            <el-table-column prop="amount" label="金额" width="80" align="right">
              <template #default="{ row }">
                ¥{{ Number(row.amount).toFixed(2) }}
              </template>
            </el-table-column>
            <el-table-column prop="status" label="状态" width="80" align="center">
              <template #default="{ row }">
                <el-tag :type="row.status === 'SUCCESS' ? 'success' : 'warning'" size="small">
                  {{ row.status === 'SUCCESS' ? '已完成' : '待支付' }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="created_at" label="创建时间" width="160">
              <template #default="{ row }">
                {{ formatDateTime(row.created_at) }}
              </template>
            </el-table-column>
            <el-table-column prop="paid_at" label="支付时间" width="160">
              <template #default="{ row }">
                {{ row.paid_at ? formatDateTime(row.paid_at) : '未支付' }}
              </template>
            </el-table-column>
            <el-table-column prop="transaction_id" label="微信交易号" min-width="200">
              <template #default="{ row }">
                {{ row.transaction_id || '无' }}
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="detailDialogVisible = false">关闭</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { Search, Refresh } from '@element-plus/icons-vue'
import {
  getOrders,
  getOrderById,
  ORDER_STATUS_OPTIONS,
  getOrderStatusText,
  getOrderStatusTagType,
  type Order,
  type OrderListParams
} from '@/api/order'
import { getParkingLots, type ParkingLot } from '@/api/parkingLot'

// 响应式数据
const loading = ref(false)
const tableData = ref<Order[]>([])
const parkingLots = ref<ParkingLot[]>([])
const detailDialogVisible = ref(false)
const currentOrder = ref<Order | null>(null)
const dateRange = ref<[string, string] | null>(null)

// 筛选表单
const filterForm = reactive<OrderListParams>({
  order_number: '',
  license_plate: '',
  contact_phone: '',
  status: '',
  parking_lot_id: undefined,
  start_date: '',
  end_date: ''
})

// 分页数据
const pagination = reactive({
  page: 1,
  pageSize: 10,
  total: 0
})

// 方法定义
/**
 * 格式化日期
 */
function formatDate(dateString: string): string {
  try {
    const date = new Date(dateString)
    return date.toLocaleString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit'
    })
  } catch (error) {
    return '格式错误'
  }
}

/**
 * 格式化日期时间（详细）
 */
function formatDateTime(dateString: string): string {
  try {
    const date = new Date(dateString)
    return date.toLocaleString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit',
      second: '2-digit'
    })
  } catch (error) {
    return '格式错误'
  }
}

/**
 * 格式化支付方式
 */
function formatPaymentMethod(paymentMethod: string): string {
  if (!paymentMethod) return '未知'

  // 如果是简单的字符串
  if (typeof paymentMethod === 'string' && !paymentMethod.startsWith('{')) {
    const methodMap: Record<string, string> = {
      'wechat_pay': '微信支付',
      'mock_wechat_pay': '模拟微信支付',
      'alipay': '支付宝',
      'mock_payment': '模拟支付'
    }
    return methodMap[paymentMethod] || paymentMethod
  }

  // 如果是 JSON 格式（包含尾款信息）
  try {
    const parsed = JSON.parse(paymentMethod)
    if (parsed.additional_payments && Array.isArray(parsed.additional_payments)) {
      const successCount = parsed.additional_payments.filter((p: any) => p.status === 'SUCCESS').length
      const totalCount = parsed.additional_payments.length
      return `微信支付 (含${totalCount}笔尾款，${successCount}笔已完成)`
    }
    return '微信支付'
  } catch (error) {
    return '微信支付'
  }
}

/**
 * 获取尾款记录列表
 */
function getAdditionalPayments(paymentMethod: string): any[] {
  if (!paymentMethod) return []

  try {
    const parsed = JSON.parse(paymentMethod)
    return parsed.additional_payments || []
  } catch (error) {
    return []
  }
}

/**
 * 加载订单列表
 */
async function loadOrders() {
  try {
    loading.value = true

    const params = {
      page: pagination.page,
      pageSize: pagination.pageSize,
      ...filterForm
    }

    // 清理空值
    Object.keys(params).forEach(key => {
      if (params[key as keyof typeof params] === '' || params[key as keyof typeof params] === undefined) {
        delete params[key as keyof typeof params]
      }
    })

    const response = await getOrders(params)

    if (response.success) {
      tableData.value = response.data.list
      pagination.total = response.data.total
    }
  } catch (error) {
    console.error('加载订单列表失败:', error)
    ElMessage.error('加载数据失败')
  } finally {
    loading.value = false
  }
}

/**
 * 加载停车场列表
 */
async function loadParkingLots() {
  try {
    // 分批加载所有停车场
    let allParkingLots: ParkingLot[] = []
    let page = 1
    const pageSize = 100 // 后端最大限制
    let hasMore = true

    while (hasMore) {
      const response = await getParkingLots({ page, pageSize })
      if (response.success) {
        allParkingLots = [...allParkingLots, ...response.data.list]
        hasMore = response.data.list.length === pageSize
        page++
      } else {
        hasMore = false
      }
    }

    parkingLots.value = allParkingLots
  } catch (error) {
    console.error('加载停车场列表失败:', error)
  }
}

/**
 * 日期范围改变处理
 */
function handleDateRangeChange(dates: [string, string] | null) {
  if (dates) {
    filterForm.start_date = dates[0]
    filterForm.end_date = dates[1]
  } else {
    filterForm.start_date = ''
    filterForm.end_date = ''
  }
}

/**
 * 搜索处理
 */
function handleSearch() {
  pagination.page = 1
  loadOrders()
}

/**
 * 重置处理
 */
function handleReset() {
  Object.assign(filterForm, {
    order_number: '',
    license_plate: '',
    contact_phone: '',
    status: '',
    parking_lot_id: undefined,
    start_date: '',
    end_date: ''
  })
  dateRange.value = null
  pagination.page = 1
  loadOrders()
}

/**
 * 分页大小改变
 */
function handleSizeChange(size: number) {
  pagination.pageSize = size
  pagination.page = 1
  loadOrders()
}

/**
 * 当前页改变
 */
function handleCurrentChange(page: number) {
  pagination.page = page
  loadOrders()
}

/**
 * 查看订单详情
 */
async function handleViewDetail(row: Order) {
  try {
    const response = await getOrderById(row.id)
    if (response.success) {
      currentOrder.value = response.data
      detailDialogVisible.value = true
    }
  } catch (error) {
    console.error('获取订单详情失败:', error)
    ElMessage.error('获取订单详情失败')
  }
}

/**
 * 拨打电话
 */
function callPhone(phoneNumber: string) {
  window.open(`tel:${phoneNumber}`)
}

/**
 * 格式化优惠券类型
 */
function formatCouponType(type: string): string {
  const typeMap: Record<string, string> = {
    'fixed': '满减券',
    'percentage': '折扣券'
  }
  return typeMap[type] || type
}

/**
 * 格式化优惠券面值
 */
function formatCouponValue(type: string, value: number): string {
  if (type === 'percentage') {
    return `${value}折`
  } else if (type === 'fixed') {
    return `${value}元`
  }
  return `${value}`
}

// 生命周期
onMounted(() => {
  loadOrders()
  loadParkingLots()
})
</script>

<style scoped>
.order-management {
  padding: 20px;
}

.page-header {
  margin-bottom: 20px;
}

.page-header h1 {
  margin: 0 0 8px 0;
  color: #333;
  font-size: 24px;
}

.page-header p {
  margin: 0;
  color: #666;
  font-size: 14px;
}

.filter-bar {
  margin-bottom: 20px;
  padding: 20px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.filter-form {
  margin: 0;
}

.table-card {
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.pagination-wrapper {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

.user-info {
  line-height: 1.4;
}

.user-phone {
  font-size: 12px;
  color: #999;
}

.amount {
  font-weight: 600;
  color: #333;
}

.final-amount {
  color: #f56c6c;
}

.discount {
  color: #67c23a;
}

.order-detail {
  margin: 20px 0;
}

.additional-payments-section {
  margin-top: 20px;
}

.additional-payments-section h4,
.fee-details-section h4,
.coupon-section h4,
.time-info-section h4 {
  margin: 0 0 10px 0;
  color: #333;
  font-size: 16px;
  padding-bottom: 8px;
  border-bottom: 1px solid #eee;
}

.fee-details-section,
.coupon-section,
.time-info-section {
  margin-top: 20px;
}

.description-text {
  color: #666;
  font-style: italic;
}

.dialog-footer {
  text-align: right;
}

.contact-phone {
  color: #409eff;
  cursor: pointer;
  text-decoration: underline;
}

.contact-phone:hover {
  color: #66b1ff;
}

.no-phone {
  color: #c0c4cc;
  font-style: italic;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .filter-form {
    display: flex;
    flex-direction: column;
    gap: 15px;
  }

  .filter-form .el-form-item {
    margin-right: 0;
    margin-bottom: 0;
  }
}
</style>
